# from datetime import datetime, time
from models import UserModel, BorrowModel, InventoryModel, BookModel
from flask import Blueprint, render_template, request, url_for, session, redirect, jsonify, flash, g, make_response
from exts import db
import datetime, time
from forms import SearchStudentForm, SearchBookForm, RegisterForm, ChangePasswordForm
from utils import RandomNumber
from io import BytesIO


# __name__代表当前模块
user = Blueprint('user', __name__)


@user.route('/user/index')
def index():
    return render_template('index.html')


@user.route('/user/user', methods=['GET', 'POST'])
def user_student():
    form = SearchStudentForm()
    return render_template('user-student.html', form=form)


@user.route('/user/book', methods=['GET', 'POST'])
def user_book():
    form = SearchBookForm()
    return render_template('user-book.html', form=form)


@user.route('/user/user_info')
def user_info():
    return render_template('user-info.html')


@user.route('/user/change_password', methods=['GET', 'POST'])
def change_password():
    if request.method == 'GET':
        form = ChangePasswordForm()
        return render_template('change-password.html', form=form)
    if request.method == 'POST':
        form = ChangePasswordForm()
        if form.password2.data != form.password.data:
            flash(u'两次密码不一致！')
        if form.validate_on_submit():
            if g.account.password == form.old_password.data:
                current_user = UserModel.query.filter_by(account_number=g.account.account_number).first()
                current_user.password = form.password.data
                db.session.commit()
                g.account.password = form.password.data
                flash(u'已成功修改密码！')
                return redirect(url_for('user.index'))
            else:
                flash(u'原密码输入错误，修改失败！')
        return render_template('change-password.html', form=form)


@user.route('/user/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        form = RegisterForm()
        return render_template("register.html", form=form)
    elif request.method == 'POST':
        form = RegisterForm()
        if form.validate_on_submit():
            account = UserModel.query.filter_by(username=form.account.data).first()
            if account is not None:
                flash(u'用户名已存在！')
                return render_template("register.html", form=form)
            else:
                card_id = RandomNumber.rand_value(0, 10)
                account_number = RandomNumber.rand_value(0, 9)
                user = UserModel()
                user.username = form.account.data
                user.password = form.password.data
                user.phone = form.phone.data
                user.balance = 0
                user.debt = False
                today_date = datetime.date.today()
                today_str = today_date.strftime("%Y-%m-%d")
                today_stamp = time.mktime(time.strptime(today_str + ' 00:00:00', '%Y-%m-%d %H:%M:%S'))
                user.join_time = int(today_stamp) * 1000
                one_year_ago = int(today_stamp) + 364 * 86400
                user.valid_date = str(one_year_ago * 1000)
                user.card_id = card_id
                user.account_number = account_number
                db.session.add(user)
                db.session.commit()
                flash('账号为：' + account_number + ' 借书卡号为：' + card_id + '\n' + '请妥善保管！')
                return redirect(url_for('login'))
        return render_template(url_for("register.html", form=form))


@user.route('/user/logout')
def logout():
    return redirect(url_for('login'))


@user.route('/user/echarts')
def echarts():
    days = []
    num = []
    today_date = datetime.date.today()
    today_str = today_date.strftime("%Y-%m-%d")
    today_stamp = time.mktime(time.strptime(today_str + ' 00:00:00', '%Y-%m-%d %H:%M:%S'))
    ten_ago = int(today_stamp) - 14 * 86400
    for i in range(0, 15):
        borr = BorrowModel.query.filter_by(borrow_time=str((ten_ago + i * 86400) * 1000)).count()
        retu = BorrowModel.query.filter_by(due_date=str((ten_ago + i * 86400) * 1000)).count()
        num.append(borr + retu)
        days.append(timestamp((ten_ago + i * 86400) * 1000))
    data = []
    for i in range(0, 15):
        item = {'name': days[i], 'num': num[i]}
        data.append(item)
    return jsonify(data)


@user.route('/user/export', methods=['GET'])
def export():
    if request.method == 'GET':
        borrowers = BorrowModel.query.all()
        response_sets = []
        for borrower in borrowers:
            borrow_time = timestamp(borrower.borrow_time)
            return_time = timestamp(borrower.return_time)
            due_date = timestamp(borrower.due_date)
            response_sets.append(
                [borrow_time, return_time, due_date, borrower.book_id, borrower.card_id, borrower.barcode])
        response = excel.make_response_from_query_sets(response_sets,
                                                       column_names=['借书时间', '归还时间', '应还时间', 'isbn',
                                                                     '借书卡号',
                                                                     '书籍条形码'], file_type='xlsx',
                                                       file_name='borrower')
        # response = make_response(bytes, 200)
        response.headers['Content-Disposition'] = 'attachment; filename=borrower.xlsx'
        response.headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        return response


@user.route('/user/find_user', methods=['POST'])
def find_user():
    user = UserModel.query.filter_by(card_id=request.form.get('card')).first()
    if user is None:
        return jsonify([])
    else:
        valid_date = timestamp(user.valid_date)
        return jsonify([{'name': user.username, 'valid_date': valid_date, 'debt': user.debt}])


@user.route('/user/find_record', methods=['POST'])
def find_record():
    records = db.session.query(BorrowModel).join(InventoryModel).join(BookModel).filter(
        BorrowModel.card_id == request.form.get('card')) \
        .with_entities(BorrowModel.barcode, InventoryModel.isbn, BookModel.book_name, BookModel.author,
                       BorrowModel.borrow_time,
                       BorrowModel.return_time, BorrowModel.due_date).all()  # with_entities啊啊啊啊卡了好久啊
    data = []
    for record in records:
        start_date = timestamp(record.borrow_time)
        due_date = timestamp(record.due_date)
        end_date = timestamp(record.return_time)
        if end_date is None:
            end_date = '未归还'
        print(record)
        item = {'barcode': record.barcode, 'book_name': record.book_name, 'author': record.author,
                'start_date': start_date, 'due_date': due_date, 'end_date': end_date}
        data.append(item)
    return jsonify(data)


def timestamp(time_num):
    if time_num is None:
        return time_num
    else:
        timestamp = float(float(time_num) / 1000)
        time_array = time.localtime(timestamp)
        print(time.strftime("%Y-%m-%d", time_array))
        return time.strftime("%Y-%m-%d", time_array)
